package com.tp.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.tp.base.BaseService;
import com.tp.base.Paginator;
import com.tp.model.sys.SysLog;
import com.tp.model.sys.SysUser;
import com.tp.utils.SQLUtils;
import com.tp.utils.StrUtils;

/**
 * 日志service
 * 
 * @author TP
 *
 */
public class LogService extends BaseService {

	private static SysLog sl = new SysLog().dao();

	/**
	 * 分页查询
	 * 
	 * @param model
	 * @param orderBy
	 * @param paginator
	 * @return
	 */
	public Page<SysLog> getPageByWhere(SysLog model, String orderBy, Paginator paginator) {
		SQLUtils sql = new SQLUtils("from " + SysLog.tableName + " t left join " + SysUser.tableName
				+ " u on t.create_id=u.id where 1=1");
		if (model.getAttrValues().length != 0) {
			sql.setAlias("t");
			// 查询条件
			sql.whereLike("log_type", model.getStr("log_type"));
			if (StrUtils.isNotEmpty(model.getStr("create_time"))) {
				String[] date = model.getStr("create_time").split(" - ");
				sql.append(" and str_to_date(t.create_time, '%Y-%m-%d')>=")
						.append("str_to_date('" + date[0].trim() + "', '%Y-%m-%d')");
				sql.append(" and str_to_date(t.create_time, '%Y-%m-%d')<=")
						.append("str_to_date('" + date[1].trim() + "', '%Y-%m-%d')");
			}
		}
		if (StrUtils.isEmpty(orderBy)) {
			sql.append(" order by t.create_time desc");
		} else {
			sql.append(" order by ").append(orderBy);
		}
		Page<SysLog> page = sl.paginate(paginator, "select t.*,u.logn_acct as create_name ", sql.toString());
		return page;
	}

	/**
	 * 删除日志
	 * 
	 * @param ids
	 * @param uid
	 * @return
	 */
	public boolean deleteObject(String[] ids) {
		if (!StrUtils.empty(ids)) {
			boolean flag = false;
			for (String id : ids) {
				SysLog dao = new SysLog();
				flag = dao.deleteById(id);
				if (!flag) {
					break;
				}
			}
			return flag;
		}
		return false;
	}

	/**
	 * 清空日志表
	 * 
	 * @return
	 */
	public boolean clearLog() {
		int i = Db.update("truncate table " + SysLog.tableName);
		if (i > 0) {
			return true;
		}
		return false;
	}
}
